package cn.itcast.nio.c4;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.nio.charset.Charset;
import java.util.Iterator;

/**
 * @Author: LDeng
 * @Date: 2021-05-13 9:47
 */
public class WriteServer {
    public static void main(String[] args) throws IOException {
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.configureBlocking(false);

        Selector selector = Selector.open();
        ssc.register(selector, SelectionKey.OP_ACCEPT);

        ssc.bind(new InetSocketAddress("localhost", 8080));
        while (true) {
            int select = selector.select();
            System.out.println("事件数量"+select);
            Iterator<SelectionKey> iterator =
                    selector.selectedKeys().iterator();
            while (iterator.hasNext()) {
                SelectionKey key = iterator.next();
                iterator.remove();
                if (key.isAcceptable()) {
                    SocketChannel sc = ssc.accept();
                    sc.configureBlocking(false);
                    SelectionKey sckey = sc.register(selector, 0, null);
                    //1，模拟向客户端发送大量数据
                    StringBuilder sb = new StringBuilder();
                    for (int i = 0; i < 1000000; i++) {
                        sb.append("a");
                    }
                    ByteBuffer buffer = Charset.defaultCharset().encode(sb.toString());
                    //2， 返回值代表实际写入的字节数
                    int write = sc.write(buffer);
                    System.out.println("第一次写===>" + write);
                    //3 , 先写一点， 然后判断是否有剩余内容
                    if (buffer.hasRemaining()) {
                        //4,关注可写事件
                        sckey.interestOps(sckey.interestOps() + SelectionKey.OP_WRITE);
                        //5, 把未写完的数据挂到sckey上
                        sckey.attach(buffer);
                    }

                } else if (key.isWritable()) {
                    ByteBuffer buffer = (ByteBuffer) key.attachment();
                    SocketChannel sc = (SocketChannel) key.channel();
                    int write = sc.write(buffer);
                    System.out.println("else if==>"+write);
                    //6 ,清理
                    if(!buffer.hasRemaining()){
                        key.attach(null);//清除buffer
                        key.interestOps(key.interestOps()-SelectionKey.OP_WRITE);//不再关注可写事件
                    }
                }
            }
        }


    }
}
